// *************************************
// * Creator:SunnyPaine
// * DateTime:2024/08/14 16:08:48
// * Description:<Description>
// * CopyRight:
// * ***********************************

using System;
using System.Threading.Tasks;
using System.Windows.Threading;

namespace SunnyPaine.Autofac.Extension.Mvvm.UI
{
    /// <summary>
    /// 提供用于协调UI线程和非UI线程操作的关键类，通过消息循环机制确保UI元素的安全更新
    /// </summary>
    public class DispathcerService : BaseService, IDispathcerService
    {
        /// <summary>
        /// 异步执行委托。
        /// </summary>
        /// <param name="action">委托方法。</param>
        /// <returns></returns>
        public Task BeginInvoke(Action action)
        {
            return base.Dispatcher.BeginInvoke(action, DispatcherPriority.Normal).Task;
        }

        /// <summary>
        /// 异步执行委托方法。
        /// </summary>
        /// <param name="action">委托方法。</param>
        /// <param name="delay">延迟执行委托方法的时长。</param>
        /// <returns></returns>
        public Task BeginInvoke(Action action, TimeSpan delay)
        {
            TaskCompletionSource<object> source = new TaskCompletionSource<object>();
            DispatcherTimer timer = new DispatcherTimer(DispatcherPriority.Normal, base.Dispatcher);
            EventHandler onTimerTick = null;
            onTimerTick = delegate
            {
                timer.Tick -= onTimerTick;
                timer.Stop();
                action();
                source.SetResult(null);
            };
            timer.Tick += onTimerTick;
            timer.Interval = delay;
            timer.Start();
            return source.Task;
        }

        /// <summary>
        /// 同步执行委托方法。
        /// </summary>
        /// <param name="action">委托方法。</param>
        public void Invoke(Action action)
        {
            base.Dispatcher.Invoke(action);
        }
    }
}